package com.yuan.base.framework;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.yuan.base.utils.ActivityManager;
import com.yuan.base.utils.ProgressUtil;
import com.yuan.base.utils.UIUtil;
import com.yuan.base.widget.iosDialog.IosProgress;

import java.util.ArrayList;


/**
 */
public abstract class BaseFrameworkActivity extends AppCompatActivity {

	protected final String TAG = this.getClass().getSimpleName();
	// 关闭键盘是否启用
	protected boolean isShouldHideInput = true;

	// 进度条
	private IosProgress progressDialog;
	// 进度条计数器
	private int progressDialogCount = 0;

	private LayoutInflater inflater;

	protected LayoutInflater getInflater() {
		if (inflater == null) {
			inflater = LayoutInflater.from(this);
		}
		return inflater;
	}

	protected abstract int getLayoutId();

	protected abstract void bindViews();


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActivityManager.getInstance().pushActivity(this);
		setContentView(getLayoutId());
		bindViews();
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onDestroy() {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
		super.onDestroy();
		ActivityManager.getInstance().popActivity(this);
	}

	public void closeSelf() {
		ActivityManager.getInstance().popActivity(this);
	}

	public void closeSelf(View view) {
		closeSelf();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		closeSelf();
	}

	public void showToast(String str) {
		UIUtil.showToast(str);
	}

	public IosProgress showProgressBar() {
		return showProgressBar("正在请求,请稍候...");
	}

	public IosProgress showProgressBar(String content) {
		if (progressDialog == null) {
			progressDialog = ProgressUtil.buildDialog(this, content);
		} else {
			progressDialog.setLabel(content);
		}
		try {
			progressDialog.show();
			progressDialogCount++;
		} catch (Exception ignored) {
		}
		return progressDialog;
	}

	public void hideProgressBar() {
		progressDialogCount--;
		if (progressDialogCount <= 0) {
			if (progressDialog != null) {
				try {
					progressDialog.dismiss();
				} catch (Exception ignored) {
				}
			}
		}
	}

	// 不考虑进度条数量,直接关闭
	public void hideProgressBarAtOnce() {
		progressDialogCount = 0;
		if (progressDialog != null) {
			try {
				progressDialog.dismiss();
			} catch (Exception ignored) {
			}
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_DOWN && isShouldHideInput) {
			// 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
			View v = getCurrentFocus();
			if (v == null) {
				return super.dispatchTouchEvent(ev);
			}
			// 点击自己时不隐藏键盘
			if (!isShouldHideInput(v, ev)) {
				return super.dispatchTouchEvent(ev);
			}
			// 点击某些view时不隐藏键盘
			for (int i = 0; i < notHideInput.size(); i++) {
				if (!isShouldHideInput(notHideInput.get(i), ev)) {
					return super.dispatchTouchEvent(ev);
				}
			}
			hideSoftInput(v.getWindowToken());
		}
		// 父类的view多点触摸有些情况下会出现数组溢出的情况.父view无法接收到触摸事件, 多点触摸时就会造成崩溃
		try {
			return super.dispatchTouchEvent(ev);
		} catch (IllegalArgumentException e) {
			return false;
		}
	}

	protected ArrayList<View> notHideInput = new ArrayList<>();

	protected void putNotHideViewId(View v) {
		notHideInput.add(v);
	}

	/**
	 * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
	 */
	protected boolean isShouldHideInput(View v, MotionEvent event) {
		if (v != null) {
			int[] l = {0, 0};
			v.getLocationInWindow(l);
			int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
			return !(event.getRawX() > left && event.getRawX() < right && event.getRawY() > top && event.getRawY() < bottom);
		}
		// 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
		return false;
	}

	/**
	 * 隐藏输入法
	 */
	protected void hideSoftInput(IBinder token) {
		if (token != null) {
			InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	/**
	 * 显示软键盘
	 */
	protected void showKeyboard(EditText editText) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
	}

	/**
	 * 隐藏软键盘
	 */
	protected void hideKeyboard() {
		if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
			if (getCurrentFocus() != null)
				hideSoftInput(getCurrentFocus().getWindowToken());
		}
	}

	protected String getStringByUI(TextView textView) {
		if (textView == null) {
			return "";
		}
		return textView.getText().toString();
	}

	protected String getStringTrimByUI(TextView textView) {
		if (textView == null) {
			return "";
		}
		return textView.getText().toString().trim();
	}

	protected String getUnNullString(String s, String defaultStr) {
		return TextUtils.isEmpty(s) ? defaultStr : s;
	}

	protected String getUnNullString(String s) {
		return TextUtils.isEmpty(s) ? "" : s;
	}

	protected void setOnClickListener(int id, View.OnClickListener onClickListener) {
		findViewById(id).setOnClickListener(onClickListener);
	}

	protected int getColorBase(int id) {
		return ContextCompat.getColor(this, id);
	}

	protected Drawable getDrawableBase(int id) {
		return ContextCompat.getDrawable(this, id);
	}
}
